package com.jd.cs.service;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.jd.cs.vo.AccessToken;
import com.jd.cs.vo.AppInfo;
import com.jd.cs.vo.TokenInfo;
import com.jd.cs.vo.UserInfo;
import com.jd.cs.common.Const;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author: lizhiwei
 * @date: 2020-07-25 22:30
 **/
@Service
public class MemTokenService {
    private Cache<String, TokenInfo> cache = CacheBuilder.newBuilder().expireAfterWrite(Const.Token.TOKEN_EXPIRE, TimeUnit.SECONDS).build();

    public TokenInfo get(String token) {
        return cache.getIfPresent(token);
    }

    public AccessToken saveToken(TokenInfo.TokenType tokenType, AppInfo appInfo, UserInfo userInfo) {
        String token = UUID.randomUUID().toString();

        // 保存token
        TokenInfo tokenInfo = new TokenInfo();
        tokenInfo.setTokenType(tokenType);
        tokenInfo.setAppInfo(appInfo);

        if (tokenType == TokenInfo.TokenType.USER) {
            tokenInfo.setUserInfo(userInfo);
        }

        cache.put(token, tokenInfo);

        return new AccessToken(token, LocalDateTime.now().plusSeconds(Const.Token.TOKEN_EXPIRE));
    }

}